package com.learning.spring.data.dao.datasource.service.impl;

import com.learning.spring.data.dao.datasource.entity.User;
import com.learning.spring.data.dao.datasource.service.IUserService;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.StatementCallback;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * ClassName: UserServiceImpl
 * Description:
 * Date: 2020/7/22 16:19 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class UserServiceImpl implements IUserService {

    /**
     * JDBC 操作数据访问，需要有固定的流程
     *
     * @param user
     * @return
     */
    @Override
    public int add(User user) {
        Connection connection = null;
        try {
            // 1. 获取连接资源
            connection = getConnection();

            // 2. 启动事务
            connection.setAutoCommit(false);

            // 3. 具体的数据访问操作和处理
            try (PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM t_user WHERE ?")) {
                preparedStatement.setString(1, "");
                preparedStatement.execute();
            }

            // 4. 提交事务
            connection.commit();
        } catch (Exception e) {
            try {
                // 5. 回滚事务
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            // 6. 释放资源
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return 0;
    }

    private Connection getConnection() {
        return null;
    }

    /**
     * JDBC 模板操作数据
     *
     * @param id
     * @return
     */
    @Override
    public int delete(int id) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.execute(new StatementCallback() {
            @Override
            public Object doInStatement(Statement stmt) throws SQLException, DataAccessException {
                // 执行业务数据操作
                ResultSet resultSet = stmt.executeQuery("SELECT * FROM t_user WHERE ?");
                return null;
            }
        });

        return 0;
    }

    @Override
    public int update(User user) {
        return 0;
    }

    @Override
    public User select(int id) {
        return null;
    }
}
